package org.example.ideavr.controller;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.example.ideavr.common.BaseException;
import org.example.ideavr.common.result.Result;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@RestController
@Slf4j
@RequestMapping("/update")
@CrossOrigin(origins = "http://localhost:5173")
@Tag(name = "文件上传模块")
public class UpdateController {

    @Operation(summary = "图片上传接口")
    @PostMapping("/img")
    public Result<String> imgUpdate(MultipartFile file){
        log.info("图片上传{}",file);

        String img = update(file, "img");
        return Result.success(img);
    }

    @Operation(summary = "游戏上传接口")
    @PostMapping("/game")
    public Result<String> gameUpdate(MultipartFile file){
        log.info("游戏上传{}",file);
        String game = update(file, "game");
        return Result.success(game);
    }

    public String update(MultipartFile file, String type){
        String originalFilename = file.getOriginalFilename();
        String extName = originalFilename.substring(originalFilename.lastIndexOf("."));
        if(!extName.equals(".exe") && type.equals("game")){
            throw new BaseException("请上传exe文件");
        }
        String fileName = UUID.randomUUID() + extName;
        log.info("新文件名{}",fileName);

        String pathname = "D:\\update\\" + type + "\\";
        File file1 = new File(pathname);
        if(!file1.exists()){
            file1.mkdirs();
        }
        try {
            file.transferTo(new File(pathname + fileName));
        } catch (IOException e) {
            throw new BaseException("上传失败");
        }

        if(extName.equals(".exe") && type.equals("game"))return fileName;
        return "$http://localhost:80/" + type + "/" + fileName;
    }


}
